package net.jiug.common.utils;

import com.sun.mail.util.MailSSLSocketFactory;
import net.jiug.common.web.base.BaseService;
import org.springframework.context.annotation.Configuration;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.logging.Logger;

/**
 * 发邮件工具类
 */
@Configuration
public class EmailUtils {

    private Session session;
    private Transport transport;
    private InternetAddress internetAddress;

    private String currentHost;
    private String currentUser;
    private String currentPassword;

    private Properties properties = System.getProperties();// 获取系统属性

    /**
     * 更新邮箱会话连接
     */
    public void updateSession(String host, Integer port, String user, String password, String nick) {
        try {
            //关闭原连接
            if(transport!=null){ transport.close(); }
            // 记忆参数，用于连接失效时恢复连接
            currentHost = host;
            currentUser = user;
            currentPassword = password;

            properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
            properties.setProperty("mail.transport.protocol", "smtp");
            //  properties.setProperty("mail.smtp.port", "587");  //不需要 默认端口
            properties.setProperty("mail.smtp.auth", "true");// 打开认证
            //  properties.put("mail.smtp.socketFactory", "javax.net.ssl.SSLSocketFactory");

            // QQ邮箱需要下面这段代码，163邮箱不需要
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);
            properties.put("mail.smtp.ssl.protocols", "TLSv1.2"); //加上这句解决问题

            // 1.获取默认session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(user, password);
                }
            });
            session.setDebug(false);

            //2、通过session得到transport对象
            Transport transport = session.getTransport();
            //3、使用用户名和授权码连上邮件服务器
            transport.connect(host, user, password);

            // 4.1设置发件人
            InternetAddress internetAddress;
            //设置自定义发件人昵称
            try {
                internetAddress = new InternetAddress(MimeUtility.encodeText(nick) + "<" + user + ">");
            } catch (UnsupportedEncodingException e) {
                internetAddress = new InternetAddress(user);
            }

            // 赋值新连接
            this.session = session;
            this.transport = transport;
            this.internetAddress = internetAddress;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送邮件
     */
    public void sendEmail(String toEmail, String title, String content) throws Exception {

        // 与检查是否连接
        if (!transport.isConnected()){
            transport.connect(currentHost,currentUser,currentPassword);
        }
        // 1.创建邮件对象
        Message message = new MimeMessage(session);
        // 1.1设置发件人
        message.setFrom(internetAddress);
        // 1.2设置接收人
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        // 1.3设置邮件主题
        message.setSubject(title);
        // 1.4设置邮件内容
        message.setContent(content, "text/html;charset=UTF-8");

        // 2、发送邮件
        transport.sendMessage(message,message.getAllRecipients());

        // 3、日志记录
        logger.info("toEmail:" + toEmail + " |title:" + title + " |content:" + content);

    }

    protected static final Logger logger = Logger.getLogger(EmailUtils.class.getName());

}